import axios from 'axios'
import router from '@/router'
import { Notify } from 'vant'
import store from './store/index'
axios.defaults.baseURL = 'http://yongyan0624.top:9090'

const request = axios.create({
  timeout: 8000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
})

//开始 加载loading
let startLoading = () => {
  store.commit('SHOW_LOADING', true)
}
//结束 取消loading加载
let endLoading = () => {
  store.commit('SHOW_LOADING', false)
}

//showFullScreenLoading() 与 tryHideFullScreenLoading() 目的是合并同一页面多个请求触发loading

let needLoadingRequestCount = 0 //声明一个变量

let showFullScreenLoading = () => {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

let tryHideFullScreenLoading = () => {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

request.interceptors.request.use((config) => {
  config.headers['Authorization'] = localStorage.getItem('token')

  // showFullScreenLoading()
  return config
})

request.interceptors.response.use(
  (success) => {
    // 业务逻辑错误
    /**
     * 404: 资源不存在
     * 401：用户未登录
     * 403: 权限不够
     * 500:服务器错误
     */
    let statusErrorCode = ['401', '400', '404', '403', '500']
    if (success.status && success.status == 200 && success.data.code) {
      if (statusErrorCode.includes(success.data.code.toString())) {
        Notify({ type: 'danger', message: success.data.msg })
      } else if (success.data.msg && success.data.code !== 200) {
        Notify({ type: 'success', message: success.data.msg })
      }
    }

    // tryHideFullScreenLoading()
    return success
  },
  (error) => {
    // 有错误响应
    if (error.response) {
      // 有响应码
      if (error.response.status) {
        // 分析响应码
        if (504 == error.response.status || 500 == error.response.status) {
          Notify({
            type: 'danger',
            message: res.msg ? res.msg : '服务器被吃了',
          })
        } else if (error.response.status == 403) {
          Notify({
            type: 'danger',
            message: res.msg ? res.msg : '权限不足o(╯□╰)o',
          })
        } else if (error.response.status == 401) {
          Notify({
            type: 'danger',
            message: res.msg ? res.msg : '用户未登录o(╯□╰)o',
          })
          router.replace('/login')
        } else {
          if (error.response.msg) {
            Notify({ type: 'danger', message: error.response.data.msg })
          } else {
            Notify({
              type: 'danger',
              message: error.response.data.msg
                ? error.response.data.msg
                : '未知错误！o(╯□╰)o',
            })
          }
        }
      } else {
        Notify({ type: 'danger', message: '未知错误！o(╯□╰)o' })
      }
    } else {
      Notify({ type: 'danger', message: '未知错误！o(╯□╰)o' })
    }

    // tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)

export default request
